﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Navigation;
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Shell;

namespace TravellingEntrepreneur
{
    public partial class App : Application
    {
        private static MainViewModel viewModel = null;

        /// <summary>
        /// A static ViewModel used by the views to bind against.
        /// </summary>
        /// <returns>The MainViewModel object.</returns>
        public static MainViewModel ViewModel
        {
            get
            {
                // Delay creation of the view model until necessary
                if (viewModel == null)
                    viewModel = new MainViewModel();

                return viewModel;
            }
        }

        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        private Dictionary<string, string> States = new Dictionary<string, string>();
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        public void GetLocation(GeoCoordinate coords)
        {
            UriBuilder fullUri = new UriBuilder("http://dev.virtualearth.net/REST/v1/Locations/"+coords.Latitude.ToString()+","+coords.Longitude.ToString()+"?o=xml&key=AsK9GHTlNLYbcN6WxCbfT-SwZh7CmGFtDYg4IamQEvTa1lkQvGqBQCcpHlmlEjGs");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
            UpdateState updateState = new UpdateState();
            updateState.AsyncRequest = request;
            request.BeginGetResponse(new AsyncCallback(HandlerLocResponse), updateState);
        }

        static readonly XNamespace Ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";
        private void HandlerLocResponse(IAsyncResult asyncResult)
        {
            UpdateState updateState = (UpdateState)asyncResult.AsyncState;
            HttpWebRequest forecastRequest = (HttpWebRequest)updateState.AsyncRequest;
            updateState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);

            Stream streamResult = null;
            try
            {
                streamResult = updateState.AsyncResponse.GetResponseStream();
                XElement xmlData = XElement.Load(streamResult);
                var location = xmlData.Element(Ns + "ResourceSets").Element(Ns + "ResourceSet").Element(Ns + "Resources").Element(Ns + "Location");

                string state = "Maryland";
                try
                {
                    state = States[(string)location.Element(Ns + "Address").Element(Ns + "AdminDistrict")];
                }
                catch { }
                App.ViewModel.ClearData();
                App.ViewModel.GetData(state);
            }
            catch (FormatException)
            {
                return;
            }
        }

        GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            if ((NetworkInterface.GetIsNetworkAvailable()))
            {
                States.Add("AL", "Alabama");
                States.Add("AK", "Alaska");
                States.Add("AZ", "Arizona");
                States.Add("AR", "Arkansas");
                States.Add("CA", "California");
                States.Add("CO", "Colorado");
                States.Add("CT", "Connecticut");
                States.Add("DE", "Delaware");
                States.Add("FL", "Florida");
                States.Add("GA", "Georgia");
                States.Add("HI", "Hawaii");
                States.Add("ID", "Idaho");
                States.Add("IL", "Illinois");
                States.Add("IN", "Indiana");
                States.Add("IA", "Iowa");
                States.Add("KS", "Kansas");
                States.Add("KY", "Kentucky");
                States.Add("LA", "Louisiana");
                States.Add("ME", "Maine");
                States.Add("MD", "Maryland");
                States.Add("MA", "Massachusetts");
                States.Add("MI", "Michigan");
                States.Add("MN", "Minnesota");
                States.Add("MS", "Mississippi");
                States.Add("MO", "Missouri");
                States.Add("MT", "Montana");
                States.Add("NE", "Nebraska");
                States.Add("NV", "Nevada");
                States.Add("NH", "New Hampshire");
                States.Add("NJ", "New Jersey");
                States.Add("NM", "New Mexico");
                States.Add("NY", "New York");
                States.Add("NC", "North Carolina");
                States.Add("ND", "North Dakota");
                States.Add("OH", "Ohio");
                States.Add("OK", "Oklahoma");
                States.Add("OR", "Oregon");
                States.Add("PA", "Pennsylvania");
                States.Add("RI", "Rhode Island");
                States.Add("SC", "South Carolina");
                States.Add("SD", "South Dakota");
                States.Add("TN", "Tennessee");
                States.Add("TX", "Texas");
                States.Add("UT", "Utah");
                States.Add("VT", "Vermont");
                States.Add("VA", "Virginia");
                States.Add("WA", "Washington");
                States.Add("WV", "West Virginia");
                States.Add("WI", "Wisconsin");
                States.Add("WY", "Wyoming");

                States.Add("AS", "American Samoa");
                States.Add("DC", "District of Columbia");
                States.Add("FM", "Federated States of Micronesia");
                States.Add("GU", "Guam");
                States.Add("MH", "Marshall Islands");
                States.Add("MP", "Northern Mariana Islands");
                States.Add("PW", "Palau");
                States.Add("PR", "Puerto Rico");
                States.Add("VI", "Virgin Islands");

                watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
                watcher.Start();
            }
            else
            {
                MessageBox.Show("A network connection is required to run" + Environment.NewLine + "this application. Please try again" + Environment.NewLine + "when you have connectivity.");

            }
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            watcher.Stop();

            GeoCoordinate location = e.Position.Location;
            GetLocation(location);
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        { 
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
            // Ensure that required application state is persisted here.
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}